const lodash = require('lodash')
import Base from '@/entities/Base'
import { dictToWhere } from '@/utils/sqlUtils'
import { UsageScope } from '@/entities/Constant'

const TaskJobDao = {
  table: 'task_job',
  pageSize: Base.pageSize,
}

TaskJobDao.initialForm = () => {
  return JSON.parse(
    JSON.stringify({
      id: 0,
      source: '{}',
      job: '{}',
      status: 0,
      enable: 1,
      usageScope: UsageScope.Spider,
    })
  )
}

TaskJobDao.jobForm = (source, usageScope) => {
  let job = TaskJobDao.initialForm()
  job.usageScope = usageScope
  job.job = JSON.stringify({
    message: '',
    triggerCron: '',
    triggerTime: '',
    cronType: 1,
  })
  job.source = JSON.stringify({
    specific: {
      is: true,
      ids: [source.id],
    },
  })
  return job
}

TaskJobDao.boolRow = (row) => {
  row.enable = Boolean(row.enable)
  return row
}

TaskJobDao.fetchAll = async (dict) => {
  let whereSql = dictToWhere(dict)
  return await Base.fetchAll(TaskJobDao.table, whereSql)
}

TaskJobDao.fetchPage = async (dict, page) => {
  let whereSql = dictToWhere(dict)
  return await Base.fetchPage(TaskJobDao.table, whereSql, page)
}

TaskJobDao.fetchOne = async (id) => {
  const whereSql = 'where id = ' + id
  return await Base.fetchOne(TaskJobDao.table, whereSql)
}

TaskJobDao.fetchCount = async (dict, page) => {
  let count = await TaskJobDao.countWhere(dict)
  let datas = await TaskJobDao.fetchPage(dict, page)
  return { count, datas }
}

TaskJobDao.countWhere = async (dict) => {
  let whereSql = dictToWhere(dict)
  console.log('whereSql', whereSql)
  return await Base.countWhere(TaskJobDao.table, whereSql)
}

TaskJobDao.saveSource = async (source, usageScope) => {
  let job = TaskJobDao.jobForm(source, usageScope)
  job.id = await TaskJobDao.save(job)
  return job
}

TaskJobDao.saveSourceJob = async (source, jobJob, jobCode, usageScope) => {
  let job = TaskJobDao.initialForm()
  job.job = jobJob
  job.jobCode = jobCode
  job.usageScope = usageScope
  job.source = {
    specific: {
      is: true,
      ids: [source.id],
    },
  }
  job.id = await TaskJobDao.save(job)
  return job
}

TaskJobDao.save = async (obj) => {
  if (!lodash.isString(obj.source)) {
    obj.source = JSON.stringify(obj.source)
  }
  if (!lodash.isString(obj.job)) {
    obj.job = JSON.stringify(obj.job)
  }
  return await Base.save(TaskJobDao.table, obj)
}

TaskJobDao.delete = async (id) => {
  return await Base.delete(TaskJobDao.table, id)
}

export { TaskJobDao }
